﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;


namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class DatabaseCheckAutoShrinkStateOn : IssueTypeCheckBase
    {

        public DatabaseCheckAutoShrinkStateOn()
        {
            IssueTypeId = 3011;
        }

        public override void Check()
        {
            try
            {
                // Database check AutoShrink is enabled 
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);


                // Query for Databases with auto shrink enabled

                var QryAutosShrink = from d in dc.Databases
                                     where d.IsAutoShrink == true
                                     && (d.DatabaseName != "distribution") && (d.DatabaseName != "master") && (d.DatabaseName != "msdb") && d.SourceDatabaseId == null
                                     select d;

                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                foreach (var database in QryAutosShrink)
                {

                    //Create new Issue

                    Issue issue = new Issue();
                    issue.IssueType = issueType;
                    issue.TargetId = database.DatabaseID;
                    issue.Description = issueType.Description.Replace("{Database}", database.DatabaseName);

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

    }
}
